package com.lawyer.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.aliyuncs.dyplsapi.model.v20170525.BindAxgResponse;
import com.google.gson.Gson;
import com.lawyer.entity.CallBlackInfo;
import com.lawyer.entity.Config;
import com.lawyer.entity.Coupon;
import com.lawyer.entity.Lawyer;
import com.lawyer.entity.LawyerMicroScoreInfo;
import com.lawyer.entity.User;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.lawyer.model.PhoneMessage;
import com.lawyer.repository.CallBlackInfoRepository;
import com.lawyer.repository.ConfigRepository;
import com.lawyer.repository.CouponRepository;
import com.lawyer.repository.LawyerMicroInfoRepository;
import com.lawyer.repository.LawyerMicroScoreInfoRepository;
import com.lawyer.repository.LawyerRepository;
import com.lawyer.repository.MealConfigurationRepository;
import com.lawyer.repository.MoneyFlowsRepository;
import com.lawyer.repository.UserMicroInfoRepository;
import com.lawyer.repository.UserRepository;
import com.lawyer.service.PushService;
import com.lawyer.service.VirtualCallService;

@RestController
@RequestMapping(value = "/call")
@Api(tags = "电话咨询相关")
@SuppressWarnings("all")
public class CallController {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserRepository userRepository;
	@Autowired
	private LawyerRepository lawyerRepository;

	@Autowired
	private UserMicroInfoRepository userMicroInfoRepository;
	@Autowired
	private LawyerMicroInfoRepository lawyerMicroInfoRepository;

	@Autowired
	private MoneyFlowsRepository moneyFlowsRepository;

	@Autowired
	private MealConfigurationRepository mealConfigurationRepository;

	@Autowired
	private LawyerMicroScoreInfoRepository lawyerMicroScoreInfoRepository;

	@Autowired
	private CouponRepository couponRepository;
	@Autowired
	private ConfigRepository configRepository;

	@Autowired
	private PushService pushService;

	@Autowired
	private VirtualCallService virtualCallService;
	@Autowired
	private CallBlackInfoRepository callBlackInfoRepository;

	@ApiOperation(httpMethod = "PUT", value = "咨询支付", notes = "咨询支付")
	@RequestMapping(value = "/consultingPay", method = RequestMethod.PUT)
	public HttpEntity<?> consultingPay(String userId, String lawyerId, Integer couponId) {
		Message msg = new Message();
		Double userChangeMoney = 0D;
		Double lawyerChangeMoney = 0D;
		BindAxgResponse bindAxgResponse = new BindAxgResponse();
		bindAxgResponse.setMessage("OK");
		bindAxgResponse.setCode("OK");
		try {
			// 是否在线:0离线,1在线
			Lawyer lawyer = lawyerRepository.findByIdAndOnLine(lawyerId, "1");

			User user = userRepository.findOne(userId);
			String secretNo = user.getSecretNo();
			String subsId = user.getSubsId();

			if (lawyer == null) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("律师不在线");
				msg.setData(1);
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}

			if (StringUtils.isEmpty(user.getPhone())) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("请在设置中绑定本机号码");
				msg.setData(1);
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}
			if (StringUtils.isEmpty(lawyer.getPhone())) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("律师暂无电话号码");
				msg.setData(1);
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}

			// 用优惠券
			if (couponId != null) {
				Coupon coupon = couponRepository.findByUserIdAndIsUsedAndId(userId, false, couponId);
				if (coupon != null) {
					Config config = configRepository.findByName("Subsidies");// 免费咨询律师补贴费用配置
					lawyerChangeMoney = Double.valueOf(config.getValue());
				}
			} else {
				// 按120元/次记费
				Config config5 = configRepository.findByName("ConsultingFee");// 律师咨询费
				Double pay = Double.valueOf(config5.getValue());// 律师咨询费用
				userChangeMoney = Double.valueOf(config5.getValue());

				if (pay > user.getBalance()) {
					msg.setCode(MessageConstant.FAILED_CODE);
					msg.setMessage("余额不足,请充值");
					msg.setData(1);
					return new ResponseEntity<>(msg, HttpStatus.OK);
				}

			}

			String phoneA = user.getPhone();
			String phoneB = lawyer.getPhone();
			String paramater = userId + "&" + lawyerId + "&" + couponId;

			if (StringUtils.isNotEmpty(subsId) && StringUtils.isNotEmpty(secretNo)) {
				virtualCallService.unbind(subsId, secretNo);
			}

			bindAxgResponse = virtualCallService.bindAxG(phoneA, phoneB, userId, lawyerId, couponId);
			userRepository.save(user);
			msg.setData(bindAxgResponse);

			logger.info("绑定结果 =" + new Gson().toJson(bindAxgResponse));
		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
			msg.setData(1);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "POST", value = "开始通话", notes = "开始通话")
	@RequestMapping(value = "/callBlackFirst", method = RequestMethod.POST)
	public HttpEntity<?> callBlackFirst(HttpServletRequest request, HttpServletResponse response) {
		PhoneMessage msg = new PhoneMessage();
		BufferedReader bufferedReader = null;
		StringBuilder sb = null;
		try {
			bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
			sb = new StringBuilder();
			String line = bufferedReader.readLine();
			while (line != null) {
				sb.append(line);
				line = bufferedReader.readLine();
				if (line != null) {
					sb.append("\n");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bufferedReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		ArrayList<CallBlackInfo> list = JSON.parseObject(sb.toString(), new TypeReference<ArrayList<CallBlackInfo>>() {
		});
		if (list != null) {
			for (CallBlackInfo callBlackInfo : list) {
				String paramater = callBlackInfo.getOut_id();
				if (paramater != null & paramater.contains("&")) {
					String[] arr = paramater.split("&");
					String lawyerId = String.valueOf(arr[1]);
					Lawyer lawyer = lawyerRepository.findOne(lawyerId);
					lawyer.setIsFree(false);// 设置为通话中
					lawyerRepository.save(lawyer);
				}
				
			}
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "POST", value = "通话结束回调接口", notes = "通话结束回调接口")
	@RequestMapping(value = "/callBlack", method = RequestMethod.POST)
	public HttpEntity<?> callBlack(HttpServletRequest request, HttpServletResponse response) {
		PhoneMessage msg = new PhoneMessage();
		logger.info("通话结束回收到回调......");
		BufferedReader bufferedReader = null;
		StringBuilder sb = null;
		try {
			bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
			sb = new StringBuilder();
			String line = bufferedReader.readLine();
			while (line != null) {
				sb.append(line);
				line = bufferedReader.readLine();
				if (line != null) {
					sb.append("\n");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bufferedReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		logger.info("通话结束回收到回调数据：" + sb.toString());
		ArrayList<CallBlackInfo> list = JSON.parseObject(sb.toString(), new TypeReference<ArrayList<CallBlackInfo>>() {
		});
		
		if (list != null) {

			for (CallBlackInfo callBlackInfo : list) {

				if (callBlackInfo.getRelease_cause() == 16 || callBlackInfo.getRelease_cause() == 31 || callBlackInfo.getRelease_cause() == 127) {

					if (!callBlackInfo.getStart_time().equals(callBlackInfo.getRelease_time())) {// 开始时间和结束相同，表示未结通

						String paramater = callBlackInfo.getOut_id();
						String[] arr = paramater.split("&");
						String userId = arr[0];
						String lawyerId = arr[1];
						Integer couponId = null;
						User user = userRepository.findOne(userId);

						if (StringUtils.isNotEmpty(arr[2]) && !"null".equals(arr[2])) {
							couponId = Integer.valueOf(arr[2]);
						}

						virtualCallService.callSettlement(userId, lawyerId, couponId);

						userRepository.save(user);

					}

				}

			}

			for (CallBlackInfo callBlackInfo : list) {
				String paramater = callBlackInfo.getOut_id();
				if (paramater != null && paramater.contains("&")) {
					String[] arr = paramater.split("&");
					String lawyerId = arr[1];
					Lawyer lawyer = lawyerRepository.findOne(lawyerId);
					lawyer.setIsFree(true);// 设置为空闲
					lawyerRepository.save(lawyer);
				}

			}

			callBlackInfoRepository.save(list);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "POST", value = "评分", notes = "评分")
	@RequestMapping(value = "/score", method = RequestMethod.POST)
	public HttpEntity<?> Score(@RequestBody LawyerMicroScoreInfo scoreInfo) {
		Message msg = new Message();
		try {
			lawyerMicroScoreInfoRepository.save(scoreInfo);
		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

}
